package org.coc.betterchicago;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.coc.betterchicago.beans.BetterChicagoUser;
import org.coc.betterchicago.beans.DAO;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

/**
 * @author manu
 *         https://github.com/yusuke/sign-in-with-twitter/blob/master/src/main
 *         /java/twitter4j/examples/signin/SigninServlet.java
 * 
 *         http://betterchicago.appspot.com/rest/test
 *         ?oauth_token=8DdPzNt4TYsCJaEDFiLlaLdZbcj5YNghGgSbiJvU
 *         &oauth_verifier=N3GTe0DtdKdcdGJR49yJcTX7ow83q0Tbncj5E9cQncM
 */
public class BetterChicagoLogin extends HttpServlet {
	private static final long serialVersionUID = -2964981864073083268L;

	// &denied=....
	// OR
	// oauth_token=Me8EZrvXqv6W09SmrhJHEEr1rL3eoNyxRQIqQcAIGm4
	// &oauth_verifier=3Bic293E3RtZq7AduyFbBCjp6rJ99RoYHwiuJg1mgX0
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Twitter twitter = new TwitterFactory(BetterChicagoAuth.CONFIGURATION).getInstance();
		try {
			if (request.getParameterValues("denied") == null) {
				HttpSession session = request.getSession();
				// Retrieve original requested token
				RequestToken originalRequestToken = (RequestToken) session.getAttribute("requestToken");
				AccessToken authenticatedAccessToken = twitter.getOAuthAccessToken(originalRequestToken);
				twitter.setOAuthAccessToken(authenticatedAccessToken);
				User authenticatedUser = twitter.verifyCredentials();

				System.out.println("User was successfully authenticated.");
				if (authenticatedUser != null) {
					DAO dao = new DAO();
					dao.putBetterChicagoUser(new BetterChicagoUser(authenticatedUser, authenticatedAccessToken));
					System.out.println("User succesfully saved to database for user: " + authenticatedUser.getScreenName());
					response.addCookie(new Cookie("theid", String.valueOf(authenticatedUser.getId())));
					System.out.println("User cookie was successfully added to response.");
				}
			} else {
				System.out.println("User cancelled the request thus received denied as request parameter.");
			}
			response.sendRedirect("xindex.html");
		} catch (TwitterException e) {
			e.printStackTrace();
			System.out.println("Something went wrong while trying to login the user.");
		}
	}
}
